import 'package:shop/tools/httpsClient.dart';
import 'package:shop/tools/storage.dart';

import '../models/pcontentModel.dart';

class CartServices {
  //  增加购物车
  static addCart(
    PContentItemModel pcontent,
    String selectedAttr,
    int buyNum,
  ) async {
    /*
   * 1.获取购物车本地存储里面的数据（cartListData）
   * */

    List? cartListData = await Storage.getData('cartList');

    if (cartListData != null) {
      // // any 如果有一个就返回true
      var hasData = cartListData.any((v) {
        return v['_id'] == pcontent.sId && v['selectedAttr'] == selectedAttr;
      });
      if (hasData) {
        for (var i = 0; i < cartListData.length; i++) {
          if (cartListData[i]['_id'] == pcontent.sId &&
              cartListData[i]['selectedAttr'] == selectedAttr) {
            cartListData[i]['count'] += buyNum;
          }
        }
        await Storage.setData("cartList", cartListData);
      } else {
        cartListData.add({
          "_id": pcontent.sId,
          "title": pcontent.title,
          "price": pcontent.price,
          "selectedAttr": selectedAttr,
          "count": buyNum,
          "pic": HttpsClient.photoUrl(pcontent.pic),
          "checked": true,
        });
        await Storage.setData("cartList", cartListData);
      }
    } else {
      List tempList = [];
      tempList.add({
        "_id": pcontent.sId,
        "title": pcontent.title,
        "price": pcontent.price,
        "selectedAttr": selectedAttr,
        "count": buyNum,
        "pic": HttpsClient.photoUrl(pcontent.pic),
        "checked": true,
      });
      await Storage.setData("cartList", tempList);
    }
  }

  //   获取购物车数据
  static Future<List> getCartListData() async {
    List? cartListData = await Storage.getData("cartList");
    if (cartListData != null) {
      return cartListData;
    } else {
      return [];
    }
  }

  //   重新存储购物车数据
  static void setCartListData(cartListData) async {
    await Storage.setData('cartList', cartListData);
  }

  //     删除购物车数据
  // static deleteHistoryData(keyWords) async {
  //   List? searchListData = await Storage.getData("searchList");
  //   if (searchListData != null) {
  //     Storage.removeData(keyWords);
  //     await Storage.setData("searchList", searchListData);
  //   }
  // }

  //   清空购物车数据
  static clearCartData() async {
    await Storage.clear("cartList");
  }

  //   获取选中的cartList数据
  static getCheckedCartData() async {
    List tempList = [];
    List? cartListData = await Storage.getData('cartList');
    if (cartListData != null) {
      for (var i = 0; i < cartListData.length; i++) {
        if (cartListData[i]['checked'] == true) {
          tempList.add(cartListData[i]);
        }
      }
      return tempList;
    } else {
      return [];
    }
  }
}
